import os
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64


# PKCS7Padding填充
def pkcs7_padding(text='明文', blockSize=1):
    paddingSize = blockSize - (len(text.encode('utf-8')) % blockSize)
    padding = bytes([paddingSize]) * paddingSize
    return text.encode('utf-8') + padding


# AES/CBC/PKCS7Padding加密
# 参数：明文text、密钥key、初始化向量iv
def encipher(text='明文', key='密钥', iv='初始化向量'):
    cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
    ciphertext = cipher.encrypt(pad(text.encode('utf-8'), AES.block_size))
    return base64.b64encode(ciphertext).decode()


# 去除PKCS7Padding填充
def pkcs7_unpadding(text='带填充的明文'):
    paddingSize = text[-1]
    return text[:-paddingSize]


# 解密
def decipher(text='明文', key='密钥', iv='初始化向量'):
    cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
    text = base64.b64decode(text)
    decipheredText = unpad(cipher.decrypt(text), AES.block_size)
    return decipheredText
